package com.gitee.slowcreator.http.file.download.okhttp;

import com.gitee.slowcreator.http.file.download.template.AbstractLocalFileDownload;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import java.io.InputStream;

/**
 * okhttp的request 可以用request中获取 所以很多地方直接传null过来
 * 避免很多地方还要考虑request的传入
 * 所以不要使用传入的request
 * 使用response去获取request
 *
 * @author zxw
 * @date 2023/6/10 17:08
 */
@Slf4j
public class OkhttpLocalFileDownload extends AbstractLocalFileDownload<Request, Response> {

    @Override
    protected String getContentDisposition(Request request, Response response) {
        return response.header("Content-Disposition");
    }

    @Override
    protected String getContentType(Request request, Response response) {
        return response.header("Content-Type");
    }

    @Override
    protected InputStream getDownloadInputStream(Request request, Response response) {

        ResponseBody body = response.body();
        if (body == null) {
            log.info("请求下载url:{},返回数据为空！", response.request().url());
            return null;
        }

        return body.byteStream();
    }

    @Override
    protected long getFileLength(Request request, Response response) {

        ResponseBody body = response.body();
        if (body == null) {
            log.info("请求url:{},返回数据为空！", response.request().url());
            return -1;
        }

        return body.contentLength();
    }

    @Override
    protected String getRequestUrl(Request request, Response response) {
        return response.request().url().toString();
    }
}
